﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Collections.Generic;
using System.Xml;
using System.Text;

/// <summary>
/// 淘宝接口部分经常用的函数
/// </summary>
public class TBCommon
{
    public TBCommon()
    {       
    }
    /// <summary>
    /// 绑定淘宝商店列表
    /// </summary>
    /// <param name="ddl">目标控件 </param>
    public void BindTBShop(DropDownList ddl)
    {
        List<Model.TaoBao.TB_SHANGDIAN> shops = new BLL.TaoBao.TB_SHANGDIAN().GetAllList();
        if (shops != null && shops.Count > 0)
        {
            ddl.DataSource = shops;
            ddl.DataTextField = "TBZH";
            ddl.DataValueField = "TBZH";
            ddl.DataBind();
        }
    }
    /// <summary>
    /// 绑定淘宝交易状态
    /// </summary>
    public void BindTBTradeStatus(DropDownList ddl)
    {
        ddl.Items.Clear();
        ddl.Items.Add(new ListItem("等待买家付款", "WAIT_BUYER_PAY"));
        ddl.Items.Add(new ListItem("未创建支付宝交易", "TRADE_NO_CREATE_PAY"));
        ddl.Items.Add(new ListItem("卖家已发货", "WAIT_BUYER_CONFIRM_GOODS"));
        ddl.Items.Add(new ListItem("买家已付款", "WAIT_SELLER_SEND_GOODS"));
        ddl.Items.Add(new ListItem("交易成功", "TRADE_FINISHED"));
        ddl.Items.Add(new ListItem("交易关闭", "TRADE_CLOSED"));
        ddl.Items.Add(new ListItem("创建关闭", "TRADE_CLOSED_BY_TAOBAO"));
        ddl.Items.Add(new ListItem("其他状态", "OTHER"));
    }
    /// <summary>
    /// 获取淘宝交易状态中文名称
    /// </summary>
    public string GetTradeStatus(string code)
    {
        if (code == null || code.Length == 0)
            return null;
        switch (code)
        {
            case "WAIT_BUYER_PAY": return "等待买家付款";
            case "TRADE_NO_CREATE_PAY": return "未创建支付宝交易";
            case "WAIT_BUYER_CONFIRM_GOODS": return "卖家已发货";
            case "WAIT_SELLER_SEND_GOODS": return "买家已付款";
            case "TRADE_FINISHED": return "交易成功";
            case "TRADE_CLOSED": return "交易关闭";
            case "TRADE_CLOSED_BY_TAOBAO": return "创建关闭";
            case "OTHER": return "其他状态";
            default: return null;
        }
    }
    /// <summary>
    /// 绑定商品交易类型
    /// </summary>    
    public void BindTBTradeType(DropDownList ddl)
    {
        ddl.Items.Clear();
        ddl.Items.Add(new ListItem("一口价", "fixed"));
        ddl.Items.Add(new ListItem("拍卖", "auction"));
    }
    /// <summary>
    /// 绑定淘宝会员性别
    /// </summary>
    public void BindTBSex(DropDownList ddl)
    {
        ddl.Items.Clear();
        ddl.Items.Add(new ListItem("男", "1"));
        ddl.Items.Add(new ListItem("女", "0"));
    }
    /// <summary>
    ///  绑定淘宝物流类型
    /// </summary>
    public void BindTBWLType(DropDownList ddl)
    {
        ddl.Items.Clear();
        ddl.Items.Add(new ListItem("卖家包邮", "free"));
        ddl.Items.Add(new ListItem("平邮", "post"));
        ddl.Items.Add(new ListItem("快递", "express"));
        ddl.Items.Add(new ListItem("EMS", "ems"));
    }
    /// <summary>
    /// 绑定淘宝物流状态
    /// </summary>
    public void BindTBWLStatus(DropDownList ddl)
    {
        ddl.Items.Clear();
        ddl.Items.Add(new ListItem("订单已创建", "CREATED"));
        ddl.Items.Add(new ListItem("订单重新创建", "RECREATED"));
        ddl.Items.Add(new ListItem("订单已取消", "CANCELLED"));
        ddl.Items.Add(new ListItem("订单已关闭", "CLOSED"));
        ddl.Items.Add(new ListItem("等候发给物流公司", "SENDING"));
        ddl.Items.Add(new ListItem("已发送给物流公司，等待接单", "ACCEPTING"));
        ddl.Items.Add(new ListItem("物流公司已接单", "ACCEPTED"));
        ddl.Items.Add(new ListItem("物流公司不接单", "REJECTED"));
        ddl.Items.Add(new ListItem("物流公司揽收成功", "PICK_UP"));
        ddl.Items.Add(new ListItem("物流公司揽收失败", "PICK_UP_FAILED"));
        ddl.Items.Add(new ListItem("物流公司丢单", "LOST"));
        ddl.Items.Add(new ListItem("对方拒签", "REJECTED_BY_RECEIVER"));
        ddl.Items.Add(new ListItem("对方已签", "ACCEPTED_BY_RECEIVER"));
    }
    /// <summary>
    /// 绑定运费承担人
    /// </summary>   
    public void BindTBWLPay(DropDownList ddl)
    {
        ddl.Items.Clear();
        ddl.Items.Add(new ListItem("买家承担运费", "buyer"));
        ddl.Items.Add(new ListItem("卖家承担运费","seller"));
    }
    /// <summary>
    /// 由淘宝订单交易号获取所属商品列表
    /// </summary>
    public List<Model.TaoBao.TB_XSJRD_SP> GetTb_Xsjrd_SpListbytid(string tid)
    {
        string sql = "select * from tb_xsjrd_sp where field1='" + tid + "'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return null;        
        List<Model.TaoBao.TB_XSJRD_SP> spList2=new List<Model.TaoBao.TB_XSJRD_SP>();
        //foreach (Model.TaoBao.TB_XSJRD_SP sp in spList)
        //    if (sp.field1 == tid)
        //        spList2.Add(sp);
        return spList2;
    }
    /// <summary>
    /// 由淘宝商店账户获取昵称
    /// </summary>    
    public string GetTaobaoNCbyZH(string zh)
    {
        string sql ="select tbnc from tb_shangdian where tbzh='"+zh+"'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return null;
        return ds.Tables[0].Rows[0][0].ToString();        
    }
    /// <summary>
    /// 由淘宝商店账号获取密码
    /// </summary>
    public string GetTBPsdbyZH(string zh)
    {
        string sql = "select pwd from tb_shangdian where tbzh='" + zh + "'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return null;
        return ds.Tables[0].Rows[0][0].ToString();                
    }
    /// <summary>
    /// 由淘宝账户获取MID
    /// </summary>   
    public int GetShopIdByZH(string zh)
    {
        string sql = "select mid from tb_shangdian where tbzh='" + zh + "'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return 0;
        return Convert.ToInt32( ds.Tables[0].Rows[0][0]); 
    }
    /// <summary>
    /// 由地区代码获取MID
    /// </summary>
    public int GetTBAreaMID(string areaCode)
    {
        string sql = "select mid from tb_diqu where dqdm='" + areaCode + "'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return 0;
        return Convert.ToInt32(ds.Tables[0].Rows[0][0]);        
    }
    /// <summary>
    /// 由地区代码获取MID
    /// </summary> 
    public int GetTBAreaMID(string areaCode, List<Model.TaoBao.TB_DIQU> areaList)
    {
        foreach (Model.TaoBao.TB_DIQU area in areaList)
            if (area.DQDM == areaCode)
                return area.MID;
        return 0;
    }
    /// <summary>
    /// 由类目代码获取MID
    /// </summary>
    public int GetTBLeiMuMID(string leiCode)
    {
        string sql = "select mid from tb_leimu where lmdm='" + leiCode + "'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return 0;
        return Convert.ToInt32(ds.Tables[0].Rows[0][0]);                
    }
    /// <summary>
    /// 由类目代码获取名称
    /// </summary>
    public string GetTBLeiMuNamebyCode(string code)
    {
        string sql = "select lmmc from tb_leimu where lmdm='" + code + "'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return null;
        return ds.Tables[0].Rows[0][0].ToString();  
    }
    /// <summary>
    /// 由类目MID判断是否为最末叶类目
    /// </summary>  
    public bool ISHasChildByMID(int mid)
    {
        string sql = "select count(*) from tb_leimu where parentId=" + mid + "";
        int ret = DBUtility.SqlHelper.ExecuteCountSql(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ret > 0)
            return true;
        return false;       
    }
    /// <summary>
    /// 由JY Pid获取Model
    /// </summary>  
    public Model.TaoBao.TB_XSJRD_JY GetJYModelbyPID(int pid)
    {
        string sql = "select Mid from tb_xsjrd_jy where pid=" + pid + "";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return null;
        int mid = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
        return new BLL.TaoBao.TB_XSJRD_JY().GetModel(mid);        
    }
    /// <summary>
    /// 由买家PId获取Model
    /// </summary>
    public Model.TaoBao.TB_XSJRD_MJ GetMJModelbyPID(int pid)
    {
        string sql = "select mid from tb_xsjrd_mj where pid=" + pid + "";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return null;
        int mid = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
        return new BLL.TaoBao.TB_XSJRD_MJ().GetModel(mid);        
    }
    /// <summary>
    ///判断宝贝是否存在
    /// </summary>
    public bool IsBaobeiExist(string iid)
    {
        string sql = "select count(*) from tb_baobei where field1='" + iid + "'";
        int ret = DBUtility.SqlHelper.ExecuteCountSql(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ret > 0)
            return true;
        return false;       
    }
    /// <summary>
    /// 判断宝贝是否存在
    /// </summary>
    public bool IsBaobeiExist(string iid, int shopMid)
    {
        string sql = "select count(*) from tb_baobei where field1='" + iid + "' and pid= "+shopMid+"";
        int ret = DBUtility.SqlHelper.ExecuteCountSql(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ret > 0)
            return true;
        return false;       
    }
    /// <summary>
    /// 由宝贝mid获取props
    /// </summary> 
    public string GetPropsbyMid(int mid)
    {
        string sql = "select sx_id,nr_id from tb_baobeiprops where pid=" + mid;
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return null;        
        string ret=null;
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            ret += ds.Tables[0].Rows[i][0].ToString() + ":" + ds.Tables[0].Rows[i][1].ToString() + ";";
        return ret;        
    }
    public struct PropValue
    {
        public string propCode;
        public string propName;
    }
    public List<PropValue> GetPropValuesbySkuProperty(string property)
    {
        int len = property.Length - property.Replace(";", "").Length+1;
        string [] pro =new string[len];
        for (int i = 0; i < len; i++)
            pro[i] = property.Split(';')[i];
        List<PropValue> valueList = new List<PropValue>();
        for (int i = 0; i < pro.Length; i++)
        {
            PropValue pp = new PropValue();
            pp.propCode =GetPropValuebyCode( pro[i].Split(':')[0]);
            pp.propName = GetPropValuebyNRID(pro[i].Split(':')[1]);
            valueList.Add(pp);
        }
        return valueList;
    }
    string GetPropValuebyCode(string code)
    {
        string sql = "select SXMC from tb_baobeiprops where sx_id='" + code + "'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return null;
        return ds.Tables[0].Rows[0][0].ToString();        
    }
    string GetPropValuebyNRID(string nrid)
    {
        string sql = "select NRMC from tb_baobeiprops where nr_id='" + nrid + "'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return null;
        return ds.Tables[0].Rows[0][0].ToString();                
    }    
    /// <summary>
    /// 由本地颜色代码获取颜色名称
    /// </summary>  
    public string GetColorNamebyId(string colorCode)
    {
        return new BLL.GUIGE1().GetMC(colorCode);
    }
    public string GetTBBaoBeiCidbyiid(string iid)
    {
        string sql = "select LMMC from TB_BaoBei where field1='" + iid + "'";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return null;
        return ds.Tables[0].Rows[0][0].ToString();
    }
    /// <summary>
    /// 显示提示信息
    /// /// </summary>
    public void ShowMessage(Page p, string msg)
    {
        ScriptManager.RegisterStartupScript(p, p.GetType(), "", "alert('" + msg + "')", true);
    }
    public DataSet GetDataFromXml(XmlDocument xml)
    {
        if (xml == null)
            return null;
        DataSet ds = new DataSet();
        XmlNodeReader reader = new XmlNodeReader(xml);
        //加载架构
        ds.ReadXmlSchema(reader); 
        foreach (DataTable dt in ds.Tables)
        {
            dt.BeginLoadData();
        }
        //加载数据        
        ds.ReadXml(reader, XmlReadMode.IgnoreSchema);
        foreach (DataTable dt in ds.Tables)
        {
            dt.BeginLoadData();
        }
        return ds;
    }
    public void chk_OnCheckedChanged(object sender, EventArgs e, GridView gv, string name)
    {
        CheckBox ckAll = (CheckBox)sender;
        foreach (GridViewRow row in gv.Rows)
        {
            CheckBox chk = (CheckBox)row.FindControl(name);
            if (chk != null)
            {
                if (ckAll.Checked)
                    chk.Checked = true;
                else
                    chk.Checked = false;
            }
        }
    }
    private int? _recordCount = null;
    //自定义翻页
    public void gv_RowCreated(object sender, GridViewRowEventArgs e, GridView gv, Page page)
    {
        #region 自定义分页样式
        if (e.Row.RowType == DataControlRowType.Pager)
        {
            LinkButton First = new LinkButton();
            LinkButton Prev = new LinkButton();
            LinkButton Next = new LinkButton();
            LinkButton Last = new LinkButton();

            TableCell tc = new TableCell();

            e.Row.Controls.Clear();

            #region 显示总记录数 每页记录数 当前页数/总页数
            tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
            if (_recordCount.HasValue)
            {
                tc.Controls.Add(new LiteralControl("总记录数：" + _recordCount.ToString()));
                tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
                tc.Controls.Add(new LiteralControl("每页显示数：" + gv.PageSize.ToString()));
                tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
            }
            tc.Controls.Add(new LiteralControl("当前页码/总页码：&nbsp;&nbsp;" + (gv.PageIndex + 1).ToString()));
            tc.Controls.Add(new LiteralControl("/"));
            tc.Controls.Add(new LiteralControl(gv.PageCount.ToString()));
            tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;"));
            #endregion

            #region “首页 上一页 下一页 尾页”按钮
            if (!String.IsNullOrEmpty(gv.PagerSettings.FirstPageImageUrl))
            {
                First.Text = "<img src='" + page.ResolveUrl(gv.PagerSettings.FirstPageImageUrl) + "' border='0'/>";
            }
            else
            {
                First.Text = gv.PagerSettings.FirstPageText;
            }
            First.CommandName = "Page";
            First.CommandArgument = "First";
            First.Font.Underline = false;

            if (!String.IsNullOrEmpty(gv.PagerSettings.PreviousPageImageUrl))
            {
                Prev.Text = "<img src='" + page.ResolveUrl(gv.PagerSettings.PreviousPageImageUrl) + "' border='0'/>";
            }
            else
            {
                Prev.Text = gv.PagerSettings.PreviousPageText;
            }
            Prev.CommandName = "Page";
            Prev.CommandArgument = "Prev";
            Prev.Font.Underline = false;


            if (!String.IsNullOrEmpty(gv.PagerSettings.NextPageImageUrl))
            {
                Next.Text = "<img src='" + page.ResolveUrl(gv.PagerSettings.NextPageImageUrl) + "' border='0'/>";
            }
            else
            {
                Next.Text = gv.PagerSettings.NextPageText;
            }
            Next.CommandName = "Page";
            Next.CommandArgument = "Next";
            Next.Font.Underline = false;

            if (!String.IsNullOrEmpty(gv.PagerSettings.LastPageImageUrl))
            {
                Last.Text = "<img src='" + page.ResolveUrl(gv.PagerSettings.LastPageImageUrl) + "' border='0'/>";
            }
            else
            {
                Last.Text = gv.PagerSettings.LastPageText;
            }
            Last.CommandName = "Page";
            Last.CommandArgument = "Last";
            Last.Font.Underline = false;
            #endregion

            #region 添加首页，上一页按钮
            if (gv.PageIndex <= 0)
            {
                First.Enabled = Prev.Enabled = false;
            }
            else
            {
                First.Enabled = Prev.Enabled = true;
            }

            tc.Controls.Add(First);
            tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
            tc.Controls.Add(Prev);
            tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
            #endregion

            #region 显示数字分页按钮
            // 当前页左边显示的数字分页按钮的数量
            int rightCount = (int)(gv.PagerSettings.PageButtonCount / 2);
            // 当前页右边显示的数字分页按钮的数量
            int leftCount = gv.PagerSettings.PageButtonCount % 2 == 0 ? rightCount - 1 : rightCount;
            for (int i = 0; i < gv.PageCount; i++)
            {
                if (gv.PageCount > gv.PagerSettings.PageButtonCount)
                {
                    if (i < gv.PageIndex - leftCount && gv.PageCount - 1 - i > gv.PagerSettings.PageButtonCount - 1)
                    {
                        continue;
                    }
                    else if (i > gv.PageIndex + rightCount && i > gv.PagerSettings.PageButtonCount - 1)
                    {
                        continue;
                    }
                }

                if (i == gv.PageIndex)
                {
                    tc.Controls.Add(new LiteralControl("<span style='color:red;font-weight:bold'>" + (i + 1).ToString() + "</span>"));
                }
                else
                {
                    LinkButton lb = new LinkButton();
                    lb.Text = (i + 1).ToString();
                    lb.CommandName = "Page";
                    lb.CommandArgument = (i + 1).ToString();

                    tc.Controls.Add(lb);
                }

                tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
            }
            #endregion

            #region 添加下一页，尾页按钮
            if (gv.PageIndex >= gv.PageCount - 1)
            {
                Next.Enabled = Last.Enabled = false;
            }
            else
            {
                Next.Enabled = Last.Enabled = true;
            }
            tc.Controls.Add(Next);
            tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
            tc.Controls.Add(Last);
            tc.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
            #endregion

            tc.ColumnSpan = gv.Columns.Count;
            e.Row.Controls.Add(tc);
        }
        #endregion
    }
}
